<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/* 
	数据统计
*/
class Count extends Base_Controller{
	
	private $corpsecret = 'pjQrOogM4feQ_oqbnZ697Civt5kGR7P3dAdUCFo-O1Y';

	public function __construct(){
		parent::__construct();
		$this->load->model('food_order_model');
	}
	
	// 发送今日报餐统计数据
	public function send_order_count(){
		$date = date('Y-m-d', strtotime('+1 day'));
		$excel = $this->save_excel('order', $date);
		$this->sendmsg_count($excel);
	}
	
	// 发送今日核餐统计数据
	public function send_check_count(){
		$date = date('Y-m-d');
		$excel = $this->save_excel('check', $date);
		$this->sendmsg_count($excel);
	}
	
	private function sendmsg_count($file){
		$this->load->library('Wework/weworkmsg', [
			'corpsecret' => $this->corpsecret
		]);
		$this->weworkmsg->agentid = 1000046;
		$upload = $this->weworkmsg->upload_media('file', [
			'file' => $file
		]);
		if(!$upload){
			$this->output_json('报表上传失败');
		}
		$res = $this->weworkmsg->send('file', [
			'touser' => 'jodjin|13597854245|WangGaosheng', #'jodjin|13597854245',
			'file' => [
				'media_id' => $upload['media_id']
			]
		]);
		echo json_encode($res);
	}
	
	// 生成excel
	public function save_excel($type = null, $date = null, $save = true){
		$gets = $this->input->get();
		if($gets['type']){
			$type = $gets['type'];
		}
		if($gets['date']){
			$date = $gets['date'];
		}
		if(isset($gets['save'])){
			$save = $gets['save'] ? true : false;
		}
		if(!$date){
			$date = date('Y-m-d');
		}
		$date = strtotime($date);
//		$rows = $this->food_order_model->get_result([
//			'validay' => $date
//		]);
        // 查询指定时间的validay的时间内容。返回给rows
        $rows = $this->food_order_model->get_result(['validay' => $date]);
		$res = [];
		foreach($rows as $row){
		    // 获取查询过后的breakfast内容，进行
			if($row['breakfast'] > 0){
			    // 传入 早餐代码，以及查询的第一条内容 一个空的数组。
				$this->_count('breakfast', $row, $res);
			}
			if($row['lunch'] > 0){
				$this->_count('lunch', $row, $res);
			}
			if($row['dinner'] > 0){
				$this->_count('dinner', $row, $res);
			}
		}
		$result = [];
		$meal_arr = [
			'breakfast' => '早餐',
			'lunch' => '中餐',
			'dinner' => '晚餐',
		];
		
		$fields = [
			'餐次',
			'部门',
			'报餐人数'
		];
		
		// 标题
		$title = date('Y年m月d日', $date);
		if('check' == $type){
			array_push($fields, '实际就餐人数', '未就餐人数', '未就餐人员');
			$title .= '就餐明细';
			foreach($res as $key => $item){
				$result[$key]['title'] = $meal_arr[$key];
				foreach($item as $k => $v){
					$miss_arr = $v['miss'];
					$miss_num = count($miss_arr);
					$result[$key]['total'] += $v['total'];
					$result[$key]['check'] += $v['check'];
					$result[$key]['miss'] += $miss_num;
					$v['miss'] = $miss_num;
					$v['miss_user'] = $miss_arr ? implode('、', $miss_arr) : '';
					$result[$key]['list'][] = $v;
				}
			}
		}else{
			$title .= '就餐人员';
			foreach($res as $key => $item){
				$result[$key]['title'] = $meal_arr[$key];
				foreach($item as $k => $v){
					unset($v['check'], $v['miss']);
					$result[$key]['total'] += $v['total'];
					$result[$key]['list'][] = $v;
				}
			}
		}
		
		/* echo json_encode($result);
		exit; */
		
		// excel
		$this->load->library('myexcel');
		$cell_names = $this->myexcel->cell_names;
		$cell_len = count($fields);
		$excel = $this->myexcel->_excel;
		$excel->setActiveSheetIndex(0);
		$sheet = $excel->getActiveSheet();
		$sheet->getDefaultStyle()->applyFromArray([
			'font' => [
				'name' => '微软雅黑',
				'size' => 10
			],
			'alignment' => [
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
				'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER
			],
			'borders' => [
				'allborders' => [
					'style' => PHPExcel_Style_Border::BORDER_THIN
				]
			]
		]);
		$sheet->getDefaultRowDimension()->setRowHeight(24);
		
		$sheet->mergeCells('A1:'.$cell_names[$cell_len - 1].'1')->setCellValue('A1', $title)->getStyle('A1')->applyFromArray([
			'font' => [
				'bold' => true,
				'size' => 16
			],
			'alignment' => [
				'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER
			]
		]);
		
		// 字段行
		for($i = 0; $i < count($fields); $i++){
			$col = $cell_names[$i];
			$value = $fields[$i];
			$sheet->getStyle($col)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
			$cell = $col.'2';
			$sheet->setCellValue($cell, $value)->getStyle($cell)->applyFromArray([
				'font' => [
					'bold' => true
				],
				'fill' => [
					'type' => PHPExcel_Style_Fill::FILL_SOLID,
					'color' => ['rgb' => 'eeeeee']
				]
			]);
			$width = strlen($value);
			if('F' == $col){
				$width = 80;
			}
			$sheet->getColumnDimension($col)->setWidth($width + 5);
		}
		
		// 数据
		$i = 3;
		foreach($result as $key => $item){
			$meal = $meal_arr[$key];
			$list = $item['list'];
			$n = $i + count($list) - 1;
			$meal_cells = 'A'.$i.':A'.$n;
			$sheet->mergeCells($meal_cells)->setCellValue('A'.$i, $meal);
			foreach($list as $data){
				$j = 1;
				foreach($data as $value){
					$col = $cell_names[$j];
					$cell = $col.$i;
					$sheet->setCellValue($cell, $value);
					$j++;
				}
				$i++;
			}
			$maxcol = $cell_names[$cell_len - 1];
			$sheet->mergeCells('A'.$i.':B'.$i)->setCellValue('A'.$i, $meal.'合计')->getStyle('A'.$i.':'.$maxcol.$i)->applyFromArray([
				'font' => [
					'bold' => true
				],
				'fill' => [
					'type' => PHPExcel_Style_Fill::FILL_SOLID,
					'color' => ['rgb' => 'FFEE58']
				]
			]);
			$sheet->setCellValue('C'.$i, $item['total']);
			if(isset($item['check'])){
				$sheet->setCellValue('D'.$i, $item['check']);
			}
			if(isset($item['miss'])){
				$sheet->setCellValue('E'.$i, $item['miss']);
			}
			$i += 1;
		}
		
		// 输出
		$filename = $title.'.xlsx';
		if($save !== true){
			header('Content-Type: applicationnd.ms-excel;charset=utf-8');
			header('Content-Disposition: attachment;filename='.urlencode($filename));
			header('Cache-Control: max-age=0');
		}
		$objWriter = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
		if($save === true){
			$save_path = ROOTPATH.'/foodexcel';
			if(!is_dir($save_path)){
				if(!mkdir($save_path, 0775, true)){
					exit('目录创建失败');
				}
			}
			$newfile = $save_path.'/'.$filename;
			// chmod($filename, 777);
			$objWriter->save($newfile);
			return $newfile;
		}else{
			$objWriter->save('php://output');
		}
	}

    /**
     * @param $type 早餐，中餐，午餐的就餐，名称用于查询。
     * @param $data 查询到的数据库数据
     * @param $array 空的数据（地址）
     */
	private function _count($type, $data, &$array){
		$part = $data['department']; // 获取部门
		$name = $data['name'];  // 获取姓名
        // 查询数组中是否 [早中晚餐][部门] 不存在
		if(!isset($array[$type][$part])){
		    // 创建这个部门
			$array[$type][$part]['department'] = $part;
		}
		// 就餐人数加1
		$array[$type][$part]['total'] += 1;
        // 判断吃饭总人数 是否不存在
		if(!isset($array[$type][$part]['check'])){
            // 创建这个 吃饭了的总人数
			$array[$type][$part]['check'] = 0;
		}
		// 如果他吃饭了
		if($data[$type] == 2){
		    // 累加1
			$array[$type][$part]['check'] += 1;
		}else{
		    // 如果没吃，就记住他名字
			$array[$type][$part]['miss'][] = $name;
		}
	}
	
}